import Vue from 'vue'
import Vuex from 'vuex'
import { Cache } from '@utils'
import { fetchPost, fetchGet } from '../axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userData: Cache.get('userData') || null,
    cartList: Cache.get('cartList') || null
  },
  mutations: {
    changeUserData (state, data) {
      state.userData = data
      Cache.set('userData', data)
    },
    async changeCartList (state) {
      const res = await fetchGet('/home/settle/cart')
      const arr = []
      Object.keys(res.data.items || {}).forEach(key => {
        arr.push({...res.data.items[key][1], ...{goodId: Number(key)}})
      })
      state.cartList = arr
      Cache.set('cartList', arr)
    }
  },
  actions: {
    clearLoginInfo ({commit}) {
      commit('changeUserData', null)
    }
  }
})

export default store